//https://leetcode.cn/problems/word-search/

class Solution {
    bool vist[7][7];
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int m, n;
public:
    bool exist(vector<vector<char>>& board, string word)
    {
        m = board.size();
        n = board[0].size();

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                {

                    vist[i][j] = true;
                    if (dfs(board, word, i, j, 1)) return true;
                }

            }
        }
        return false;

    }

    bool dfs(vector<vector<char>>& board, string word, int i, int j, int pos)
    {
        if (pos == word.size())
        {
            return true;
        }

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && board[x][y] == word[pos])
            {
                vist[x][y] = true;
                if (dfs(board, word, x, y, pos + 1)) return true;
                vist[x][y] = false;
            }
        }
        vist[i][j] = false;
        return false;
    }
};